<?php

namespace App\Http\Controllers\Purchase;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusExpenseVoucherInfo;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Order\SaleorderController;
use App\Http\Validate\Refund\CustomRefund;
use App\Models\Balance\Balance;
use App\Models\Custom\Custom;
use App\Models\Manger\Manger;
use App\Models\Purchase\ExpenseVoucherInfoPay;
use App\Models\Purchase\ExpenseVoucherInfoPayApprove;
use App\Models\Refund\CustomRefund as ModelCustomRefund;
use App\Models\Settle\SettleCompany;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ExpenseVoucherInfoPayController extends BaseController
{
    //1待审核，2审核中，3审核成功，4审核失败，5撤审
    protected static $audit_status = ['1'=>'待审核','2'=>'审核中','3'=>'审核成功','4'=>'审核失败','5'=>'撤审'];
    public function dopostadd(Request $request)
    {
        $params = [
            'expense_voucher_info_id',
            'company_name',
            'expense_name',
            'expense_type',
            'use_desc',
            'payment_bank',
            'payment_account_name',
            'payment_account_number',
            'payment_open_bank',
            'open_bank_account_number',
            'amount',
            'urgent_remark',
            'payment_receipt',
            'approve_id1',
            'approve_id2',
            'payment',
        ];

        $req_data = $request->only($params);
        if(!isset($req_data['payment_bank']) || empty($req_data['payment_bank'])){
            return response()->json(['code'=>'001','msg'=>'付款银行不能为空']);
        }
        if(!isset($req_data['payment_account_name']) || empty($req_data['payment_account_name'])){
            return response()->json(['code'=>'001','msg'=>'付款户名不能为空']);
        }
        if(!isset($req_data['payment_account_number']) || empty($req_data['payment_account_number'])){
            return response()->json(['code'=>'001','msg'=>'付款账号不能为空']);
        }
        if(!isset($req_data['amount']) || empty($req_data['amount'])){
            return response()->json(['code'=>'001','msg'=>'费用金额不能为空']);
        }
        if(!isset($req_data['urgent_remark']) || empty($req_data['urgent_remark'])){
            return response()->json(['code'=>'001','msg'=>'加急标识不能为空']);
        }
        if(!isset($req_data['approve_id1']) || empty($req_data['approve_id1'])){
            return response()->json(['code'=>'001','msg'=>'统审审批不能为空']);
        }
        if(!isset($req_data['approve_id2']) || empty($req_data['approve_id2'])){
            return response()->json(['code'=>'001','msg'=>'操盘审批不能为空']);
        }
        $amount = SaleorderController::amountTransformIntoCent($req_data['amount']);
        if($amount <= 0){
            return response()->json(['code'=>'001','msg'=>'付款金额必须大于0']);
        }
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $data = [];

        if(isset($req_data['company_name'])) $data['company_name'] = $req_data['company_name'];
        if(isset($req_data['expense_name'])) $data['expense_name'] = $req_data['expense_name'];
        if(isset($req_data['expense_type'])) $data['expense_type'] = $req_data['expense_type'];
        if(isset($req_data['use_desc'])) $data['use_desc'] = $req_data['use_desc'];
        if(isset($req_data['payment_receipt'])) $data['payment_receipt'] = $req_data['payment_receipt'];
        if(isset($req_data['payment_open_bank'])) $data['payment_open_bank'] = $req_data['payment_open_bank'];
        if(isset($req_data['open_bank_account_number'])) $data['open_bank_account_number'] = $req_data['open_bank_account_number'];

        if(isset($req_data['payment'])){
            $data['payment'] = json_encode($req_data['payment']);
        }
        if(!isset($req_data['expense_voucher_info_id']) || empty($req_data['expense_voucher_info_id'])){
            return response()->json(['code'=>'001','msg' => '费用单id不能为空']);
        }else{
            $isExistExpenseVoucherInfo = \App\Models\Chanjet\TplusExpenseVoucherInfo::where('id',$req_data['expense_voucher_info_id'])->first();
            if(!$isExistExpenseVoucherInfo){
                return response()->json(['code'=>'001','msg' => '费用单id非法']);
            }
            $expense_voucher_info_id = $isExistExpenseVoucherInfo->id;
        }
        $data += [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'expense_voucher_info_id' => $expense_voucher_info_id,
            'payment_bank_id' => $req_data['payment_bank'],
            'payment_bank' => SettleCompany::where('id',$req_data['payment_bank'])->value('settle_company_name'),
            'payment_account_name' => $req_data['payment_account_name'],
            'payment_account_number' => $req_data['payment_account_number'],
            'amount' => $amount,
            'urgent_remark' => $req_data['urgent_remark'],
            'create_at' => time()
        ];
        $data_approve = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'approve_id1' => $req_data['approve_id1'],
            'approve_id2' => $req_data['approve_id2'],
            'manger_name' => Manger::where('id',$manger_id)->value('realname'),
            'approve_id1_name' => Manger::where('id',$req_data['approve_id1'])->value('realname'),
            'approve_id2_name' => Manger::where('id',$req_data['approve_id2'])->value('realname'),
            'create_at' => time()
        ];
        DB::beginTransaction();
        try {

            $createId = ExpenseVoucherInfoPay::create($data)->id;
            $data_approve += ['expense_voucher_info_pay_id'=>$createId];
            $data_approve += ['expense_voucher_info_id'=>$expense_voucher_info_id];
            ExpenseVoucherInfoPayApprove::create($data_approve);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '费用单付款失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '费用单付款成功']);
    }

    //基础列表
    public function getList(Request $request){
        $isgetall = $request->isgetall ?? 0;
        $list = ExpenseVoucherInfoPay::getList($request, $this->mangerinfo, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }
    //统审列表
    public function gettslist(Request $request){
        $isgetall = $request->isgetall ?? 0;
        $list = ExpenseVoucherInfoPay::getListOne($request, $this->mangerinfo, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }
    //操盘列表
    public function getcplist(Request $request){
        $isgetall = $request->isgetall ?? 0;
        $list = ExpenseVoucherInfoPay::getListTwo($request, $this->mangerinfo, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }
    //办款列表
    public function getpaymentlist(Request $request){
        $isgetall = $request->isgetall ?? 0;
        $list = ExpenseVoucherInfoPay::getListThree($request, $this->mangerinfo, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }


    /***
     *
     * 撤审
     *
    */
    public function docancel(Request $request){
        $id = $request->id;
        if(empty($id)){
            return response()->json(['code'=>'001','msg'=>'请求参数异常']);
        }
        $ids = $id;
        if(!is_array($id)){
            $ids = explode(',',$id);
        }
        foreach ($ids as $item){
            $expenseInfo = ExpenseVoucherInfoPay::with("approve")->where('id',$item)->first();
            if(!$expenseInfo){
                return response()->json(['code'=>'001','msg'=>'付款数据获取失败']);
            }
            //1待审核，2审核中，3审核成功，4审核失败，5撤审
            if(!in_array($expenseInfo['approve']['audit_status'],[1,2])){
                return response()->json(['code'=>'001','msg'=>'非审核数据']);
            }
        }



        $res = ExpenseVoucherInfoPayApprove::whereIn('expense_voucher_info_pay_id',$ids)->update([
            'audit_status' => 5,
            'update_at' => time(),
            'ts_at' => 0,
            'cp_at' => 0
        ]);
        if($res > 0){
            return response()->json(['code'=>'000','msg'=>'撤审成功']);
        }else{
            return response()->json(['code'=>'001','msg'=>'撤审失败']);
        }
    }

    /***
     *
     * 统审审核,批量审核  id 字符串
     *
     */
    public function dotsaudit(Request $request){
        if(empty($request->id)){
            return response()->json(['code'=>'001','msg'=>'id不能为空']);
        }
        $id = $request->id;
        $audit_status = $request->audit_status;
        if(empty($id)){
            return response()->json(['code'=>'001','msg'=>'请求参数异常']);
        }
        $ids = $id;
        if(!is_array($id)){
            $ids = explode(',',$id);
        }
        foreach ($ids as $item){
            $expenseInfo = ExpenseVoucherInfoPay::with("approve")->where('id',$item)->first();
            if(!$expenseInfo){
                return response()->json(['code'=>'001','msg'=>'付款数据获取失败']);
            }else{
                $expenseInfo = $expenseInfo->toArray();
            }
            //1待审核，2审核中，3审核成功，4审核失败，5撤审
            if(!in_array($expenseInfo['approve']['audit_status'],[1])){

                return response()->json(['code'=>'001','msg'=>'统审已审核']);
            }
            if($expenseInfo['approve']['ts_at'] !== 0){
                return response()->json(['code'=>'001','msg'=>'数据异常']);
            }
        }
        $res = ExpenseVoucherInfoPayApprove::whereIn('expense_voucher_info_pay_id',$ids)->update([
            'ts_at' => time(),
            'audit_status' => $audit_status,
            'update_at' => time()
        ]);
        if($res > 0){
            return response()->json(['code'=>'000','msg'=>'审核成功']);
        }else{
            return response()->json(['code'=>'001','msg'=>'审核失败']);
        }
    }

    /***
     *
     * 操盘审核  通过/驳回
     *
     */
    public function docpaudit(Request $request){
        if(empty($request->id)){
            return response()->json(['code'=>'001','msg'=>'id不能为空']);
        }
        $id = $request->id;
        $audit_status = $request->audit_status;

        $ids = $id;
        if(!is_array($id)){
            $ids = explode(',',$id);
        }
        foreach ($ids as $item){
            $expenseInfo = ExpenseVoucherInfoPay::with("approve")->where('id',$item)->first();
            if(!$expenseInfo){
                return response()->json(['code'=>'001','msg'=>'付款数据获取失败']);
            }else{
                $expenseInfo = $expenseInfo->toArray();
            }
            //1待审核，2审核中，3审核成功，4审核失败，5撤审
            if(!in_array($expenseInfo['approve']['audit_status'],[2])){
                return response()->json(['code'=>'001','msg'=>'操盘已审核']);
            }
            if($expenseInfo['approve']['cp_at'] !== 0){
                return response()->json(['code'=>'001','msg'=>'数据异常']);
            }
        }

        $res = ExpenseVoucherInfoPayApprove::whereIn('expense_voucher_info_pay_id',$ids)->update([
            'cp_at' => time(),
            'audit_status' => $audit_status,
            'update_at' => time()
        ]);
        if($res > 0){
            return response()->json(['code'=>'000','msg'=>'审核成功']);
        }else{
            return response()->json(['code'=>'001','msg'=>'审核失败']);
        }
    }
}
